from django.shortcuts import render

# Create your views here.
from django.views import View
import uuid, json
from django import http
from . import constants
# from celery_tasks.sms.tasks import send_sms_code
from verifications.libs.yuntongxun.ccp_sms import CCP

from django_redis import get_redis_connection

from .libs.captcha.captcha import captcha

# Create your views here.

import random, logging

# 创建日志输出器
logger = logging.getLogger('django')

class SMSCodeView(View):
    """短信验证码"""

    def post(self, request):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # 接收参数
        json_dict=json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        image_code_client = json_dict.get('text')
        id = json_dict.get('id')

        # 校验参数
        if not all([image_code_client, id]):
            return http.JsonResponse({'code': 3001, 'errmsg': '缺少必传参数'})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({'code': 3002, 'errmsg': '图形验证码失效'})
        # 删除图形验证码，避免恶意测试图形验证码
        redis_conn.delete('img_%s' % id)
        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_client.lower() != image_code_server.lower():  # 转小写后比较
            return http.JsonResponse({'code': 3003, 'errmsg': '输入图形验证码有误'})

        # 生成短信验证码：生成6位数验证码
        phonecode = '%06d' % random.randint(0, 999999)
        logger.info(phonecode)
        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, phonecode)
        # 发送短信验证码
        CCP().send_template_sms(mobile,[phonecode, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SEND_SMS_TEMPLATE_ID)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    """图形验证码"""
    def get(self,request):

        """
                :param request: 请求对象
                :param cur: 唯一标识图形验证码所属于的用户
                :return: image/jpg
                """
        cur = request.GET.get('cur')
        print(cur)
        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图形验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % cur, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图形验证码
        return http.HttpResponse(image, content_type='image/jpg')

